<?php
// +----------------------------------------------------------------------
// | RXThinkCMF_EVTP5.1_PRO前后端分离旗舰版框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2021 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | 作者: ZhangXuanNeng <rxthinkcmf@163.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;

use app\admin\model\User;

/**
 * 用户管理-服务类
 * @author ZhangXuanNeng
 * @since 2020/11/19
 * Class UserService
 * @package app\admin\service
 */
class UserService extends BaseService
{
    /**
     * 构造函数
     * @author ZhangXuanNeng
     * @since 2020/11/19
     * UserService constructor.
     */
    public function __construct()
    {
        $this->model = new User();
    }

    /**
     * 获取数据列表
     * @return array
     * @since 2020/11/19
     * @author ZhangXuanNeng
     */
    public function getList()
    {
        $param = request()->param();

        // 查询条件
        $map = [];

        // 用户账号
        $username = getter($param, "username");
        if ($username) {
            $map[] = ["username", 'like', "%{$username}%"];
        }
        // 用户姓名
        $realname = getter($param, "realname");
        if ($realname) {
            $map[] = ['realname', 'like', "%{$realname}%"];
        }
        // 用户性别
        $gender = getter($param, "gender");
        if ($gender) {
            $map[] = ['gender', '=', $gender];
        }
        return parent::getList($map, "id asc"); // TODO: Change the autogenerated stub
    }

    /**
     * 添加或编辑
     * @return mixed
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\PDOException
     * @since 2020/11/19
     * @author ZhangXuanNeng
     */
    public function edit()
    {
        // 请求参数
        $data = request()->param();
        // 用户名
        $username = trim($data['username']);
        // 密码
        $password = trim($data['password']);
        // 添加时设置密码
        if (empty($data['id'])) {
            $data['password'] = get_password($password . $username);
            // 用户名重复性验证
            $count = $this->model
                ->where("username", '=', $username)
                ->where("mark", "=", 1)
                ->count();
            if ($count > 0) {
                return message("系统中已存在相同的用户名", false);
            }
            $count = $this->model
                ->where("mobile", '=', $data['mobile'])
                ->where("mark", "=", 1)
                ->count();
            if ($count > 0) {
                return message("系统中已存在相同的手机号", false);
            }
        } else {
            if(!$password){
                unset($data['password']);
            }else{
                $data['password'] = get_password($password . $username);
            }
            // 用户名重复性验证
            $count = $this->model
                ->where("username", '=', $username)
                ->where("id", "<>", $data['id'])
                ->where("mark", "=", 1)
                ->count();
            if ($count > 0) {
                return message("系统中已存在相同的用户名", false);
            }
            $count = $this->model
                ->where("mobile", '=', $data['mobile'])
                ->where("id", "<>", $data['id'])
                ->where("mark", "=", 1)
                ->count();
            if ($count > 0) {
                return message("系统中已存在相同的手机号", false);
            }
        }

        // 头像处理
//        $avatar = getter($data, 'avatar');
//        if (strpos($avatar, "temp")) {
//            $data['avatar'] = save_image($avatar, 'user');
//        } else {
//            $data['avatar'] = str_replace(IMG_URL, "", $data['avatar']);
//        }
//
//        // 头像处理
//        $avatar = getter($data, 'avatar');
//        if (strpos($avatar, "temp")) {
//            $data['avatar'] = save_image($avatar, 'user');
//        } else {
//            $data['avatar'] = str_replace(IMG_URL, "", $data['avatar']);
//        }

        // 出生日期
//        if ($data['birthday']) {
//            $data['birthday'] = strtotime($data['birthday']);
//        }

        // 城市数据处理
//        $city = $data['city'];
//        if (!empty($city)) {
//            $data['province_code'] = $city[0];
//            $data['city_code'] = $city[1];
//            $data['district_code'] = $city[2];
//        } else {
//            $data['province_code'] = 0;
//            $data['city_code'] = 0;
//            $data['district_code'] = 0;
//        }
//        unset($data['city']);

        $error = "";
        $result = $this->model->edit($data, $error);
        if (!$result) {
            return message($error, false);
        }

        // 删除用户整体缓存
        $this->model->cacheDAll();

        // 删除已存在的用户角色关系数据
        $userRoleService = new UserRoleService();
        $userRoleService->deleteUserRole($result);
        // 插入用户角色关系数据
        $userRoleService->insertUserRole($result, $data['role_ids']);
        return message();
    }

    /**
     * 获取用户信息
     * @param $userId
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @since 2020/11/19
     * @author ZhangXuanNeng
     */
    public function getUserInfo($userId)
    {
        $userInfo = $this->model->getInfo($userId);

        // 返回参数
        $result = array();
        $result['id'] = $userInfo['id'];
        $result['avatar'] = $userInfo['avatar'];
        $result['realname'] = $userInfo['realname'];
        $result['nickname'] = $userInfo['nickname'];
        $result['gender'] = $userInfo['gender'];
        $result['mobile'] = $userInfo['mobile'];
        $result['email'] = $userInfo['email'];
        $result['address'] = $userInfo['address'];
        $result['intro'] = $userInfo['intro'];
        $result['roles'] = [];
        $result['authorities'] = [];

        // 权限节点列表
        $menuService = new MenuService();
        $permissionList = $menuService->getPermissionsList($userId);
        $result['permissionList'] = $permissionList;
        return message("操作成功", true, $result);
    }

    /**
     * 更新个人资料
     * @param $userId 用户ID
     * @return array
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\PDOException
     * @author ZhangXuanNeng
     * @since 2021/4/23
     */
    public function updateUserInfo($userId)
    {
        // 参数
        $param = request()->param();
        // 个人信息
        $data = [
            'id' => $userId,
            'realname' => $param['realname'],
            'nickname' => $param['nickname'],
            'gender' => $param['gender'],
            'mobile' => $param['mobile'],
            'email' => $param['email'],
            'intro' => $param['intro'],
        ];
        // 头像处理
        $avatar = isset($param['avatar']) ? $param['avatar'] : "";
        if (strpos($avatar, "data:image") !== false) {
            $expData = explode(';', $avatar);
            $fileInfo = explode('/', $expData[0]);
            $fileExt = $fileInfo[1] == 'jpeg' ? 'jpg' : $fileInfo[1];
            // 文件存储路径
            $filePath = create_image_path("user", $fileExt);

            // 获取图片流
            $item = explode(',', $avatar);
            file_put_contents(ATTACHMENT_PATH . $filePath, base64_decode($item[1]));

            $data['avatar'] = $filePath;
        } else {
            $data['avatar'] = str_replace(IMG_URL, "", $param['avatar']);
        }
        $result = $this->model->edit($data);
        if (!$result) {
            return message("更新资料信息失败", false);
        }
        return message("更新资料信息成功");
    }

    public function getPromoteLists(){
        $result = $this->model
            ->where('is_promote',1)
            ->page(PAGE, PERPAGE)
            ->order('id desc')
            ->field('id,realname')
            ->select();

        //获取数据总数
        $count = $this->model->where('is_promote',1)->count();

        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $result,
            "count" => $count,
        );
        return $message;
    }
    /**
     * 修改密码
     * @param $userId 用户ID
     * @return mixed
     * @throws \think\db\exception\BindParamException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @since 2020/11/19
     * @author ZhangXuanNeng
     */
    public function updatePwd($userId)
    {
        // 获取参数
        $param = request()->param();
        // 原始密码
        $oldPassword = trim(getter($param, "oldPassword"));
        if (!$oldPassword) {
            return message("旧密码不能为空", false);
        }
        // 新密码
        $newPassword = trim(getter($param, "newPassword"));
        if (!$newPassword) {
            return message("新密码不能为空", false);
        }
        $userInfo = $this->model->getInfo($userId);
        if (!$userInfo) {
            return message("用户信息不存在", false);
        }
        if ($userInfo['password'] != get_password($oldPassword . $userInfo['username'])) {
            return message("旧密码输入不正确", false);
        }
        $item = [
            'id' => $userId,
            'password' => get_password($newPassword . $userInfo['username']),
        ];
        $result = $this->model->edit($item);
        if (!$result) {
            return message("修改失败", false);
        }
        return message("修改成功");
    }

    /**
     * 重置密码
     * @return mixed
     * @throws \think\db\exception\BindParamException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author ZhangXuanNeng
     * @since 2020/11/19
     */
    public function resetPwd()
    {
        // 获取参数
        $param = request()->param();
        // 用户ID
        $userId = getter($param, "id");
        if (!$userId) {
            return message("用户ID不能为空", false);
        }
        $userInfo = $this->model->getInfo($userId);
        if (!$userInfo) {
            return message("用户信息不存在", false);
        }
        $item = [
            'id' => $param['id'],
            'password' => get_password("123456" . $userInfo['username']),
        ];
        $result = $this->model->edit($item);
        if (!$result) {
            return message("重置密码失败", false);
        }
        return message("重置密码成功");
    }

}